const mongoose = require("mongoose");

// Subdocument for each item sold
const SalesItemSchema = new mongoose.Schema(
  {
    item: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Item",
      required: true,
    },
    quantity: { type: Number, required: true },
    unitPrice: { type: Number, required: true },
    discount: { type: Number, default: 0 },
    tax: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Tax",
      required: false,
    },
    taxAmount: { type: Number, default: 0 },
    subtotal: { type: Number, required: true },
  },
  { _id: false }
);

// Subdocument for each payment entry
const SalesPaymentSchema = new mongoose.Schema(
  {
    // A unique payment code for each payment
    paymentCode: { type: String, unique: true },
    
    amount: { type: Number, required: true },
    paymentType: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "PaymentType",
      required: true,
    },
    account: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Account",
      required: false,
    },
    paymentNote: { type: String, default: "" },
    paymentDate: { type: Date, default: Date.now }
  },
  { _id: false }
);

const SalesSchema = new mongoose.Schema(
  {
    warehouse: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Warehouse",
      required: true,
    },
    customer: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "CustomerData",
      required: true,
    },
    
    createdBy: {
      type: mongoose.Schema.Types.ObjectId,
      refPath: "createdByModel",
      required: false, 
    },
    createdByModel: {
      type: String,
      enum: ["User", "Admin"],
      required: false,
    },
    saleCode: { type: String, required: true },
    saleDate: { type: Date, default: Date.now },
    referenceNo: { type: String, default: "" },

    items: [SalesItemSchema],

    otherCharges: { type: Number, default: 0 },
    discountCouponCode: { type: String, default: "" },
    couponType: { type: String, default: "" },
    couponValue: { type: Number, default: 0 },
    discountOnBill: { type: Number, default: 0 },
    note: { type: String, default: "" },

    payments: [SalesPaymentSchema],

    subtotal: { type: Number, required: true },
    grandTotal: { type: Number, required: true },

    status: {
      type: String,
      enum: ["Draft", "Completed", "Cancelled"],
      default: "Draft",
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model("Sales", SalesSchema);
